package com.meevle.web.tags;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.JspContext;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;

import com.meevle.business.SetDelegate;
import com.meevle.business.SlotDelegate;
import com.meevle.vo.SetVO;
import com.meevle.vo.SlotCommentVO;
import com.meevle.vo.SlotVO;
import com.meevle.vo.UserVO;

public class GetUserSetsTag extends SimpleTagSupport {

	private String username;
	private SetDelegate object;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public SetDelegate getObject() {
		return object;
	}

	public void setObject(SetDelegate object) {
		this.object = object;
	}

	public void doTag() {
		List<SetVO> sets = new ArrayList<SetVO>(0);
		double[] averageRatings = null;
		try {
			sets = SetDelegate.getAllSetsByUser(new UserVO(username));
			averageRatings = new double[sets.size()];
			if (sets.size() > 0) {
				double noemerSet = sets.size();
				for (int i = 0; i < sets.size(); i++) {
					double sumSet = 0;
					List<SlotVO> slots = SetDelegate.getAllSlots(sets.get(i));
					if (slots.size() > 0) {
						double noemerSlots = slots.size();
						double sumAverageSlots = 0;
						for (SlotVO slot : slots) {
							List<SlotCommentVO> comments = SlotDelegate
									.getSlotComments(slot);
							if (comments.size() > 0) {
								double sumSlot = 0;
								for (SlotCommentVO comment : comments) {
									sumSlot += comment.getRating();
								}

								sumAverageSlots += sumSlot / comments.size();
							}
						}// end loop over all the slots of a set
						averageRatings[i] = sumAverageSlots / slots.size();
					}
				}// end loop over all the sets
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		JspContext context = getJspContext();

		context.setAttribute("userSets", sets);
		if (averageRatings == null) {
			averageRatings = new double[] { 0 };
		}
		context.setAttribute("averageRatings", averageRatings);
		JspFragment body = getJspBody();
		try {
			body.invoke(null);
		} catch (JspException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			;
		}

	}
}
